package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DefaultZeroValueUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.BdmGoodDto;
import com.ruoyi.system.domain.vo.BdmOrderItemVo;
import com.ruoyi.system.domain.vo.applet.AppletOrderItemVo;
import com.ruoyi.system.domain.vo.applet.AppletRemainToBeEvaluated;
import com.ruoyi.system.enums.BdmBalanceChangeEnum;
import com.ruoyi.system.enums.BdmOrderEnum;
import com.ruoyi.system.mapper.BdmOrderItemMapper;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单项目Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-13
 */
@Service
public class BdmOrderItemServiceImpl extends ServiceImpl<BdmOrderItemMapper, BdmOrderItem> implements IBdmOrderItemService {
    @Autowired
    private BdmOrderItemMapper bdmOrderItemMapper;

    @Autowired
    private IBdmUserService bdmUserService;

    @Autowired
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private IBdmRoyaltyRecordService bdmRoyaltyRecordService;

    @Autowired
    private BdmUserMapper bdmUserMapper;


    @Autowired
    private IDistributionService distributionService;

    @Autowired
    private IBdmOrderService bdmOrderService;




    /**
     * 查询订单项目
     *
     * @param id 订单项目主键
     * @return 订单项目
     */
    @Override
    public BdmOrderItem selectBdmOrderItemById(Long id) {
        return bdmOrderItemMapper.selectBdmOrderItemById(id);
    }

    /**
     * 搜索订单商品列表
     *
     * @param orderIds
     * @return
     */
    @Override
    public List<AppletOrderItemVo> selectBdmOrderItemByIds(List<String> orderIds) {
        return bdmOrderItemMapper.selectBdmOrderItemByIds(orderIds);
    }

    /**
     * 查询订单项目列表
     *
     * @param bdmOrderItem 订单项目
     * @return 订单项目
     */
    @Override
    public List<BdmOrderItem> selectBdmOrderItemList(BdmOrderItem bdmOrderItem) {
        return bdmOrderItemMapper.selectBdmOrderItemList(bdmOrderItem);
    }

    /**
     * 新增订单项目
     *
     * @param bdmOrderItem 订单项目
     * @return 结果
     */
    @Override
    public int insertBdmOrderItem(BdmOrderItem bdmOrderItem) {
        bdmOrderItem.setCreateTime(DateUtils.getNowDate());
        return bdmOrderItemMapper.insertBdmOrderItem(bdmOrderItem);
    }

    /**
     * 修改订单项目
     *
     * @param bdmOrderItem 订单项目
     * @return 结果
     */
    @Override
    public int updateBdmOrderItem(BdmOrderItem bdmOrderItem) {
        bdmOrderItem.setUpdateTime(DateUtils.getNowDate());
        return bdmOrderItemMapper.updateBdmOrderItem(bdmOrderItem);
    }

    /**
     * 批量删除订单项目
     *
     * @param ids 需要删除的订单项目主键
     * @return 结果
     */
    @Override
    public int deleteBdmOrderItemByIds(Long[] ids) {
        return bdmOrderItemMapper.deleteBdmOrderItemByIds(ids);
    }

    /**
     * 删除订单项目信息
     *
     * @param id 订单项目主键
     * @return 结果
     */
    @Override
    public int deleteBdmOrderItemById(Long id) {
        return bdmOrderItemMapper.deleteBdmOrderItemById(id);
    }

    /**
     * 查询 云库存商品
     */
    @Override
    public List<BdmGoodDto> selectGoodItemList(List<Long> orderItemIds) {

        return bdmOrderItemMapper.selectGoodItemList(orderItemIds);
    }

    /**
     * 查询未评价订单项
     */
    @Override
    public List<AppletRemainToBeEvaluated> remainToBeEvaluated() {
        Long userId = SecurityUtils.getUserId();
        return bdmOrderItemMapper.remainToBeEvaluated(userId);
    }

    @Override
    public List<BdmOrderItemVo> getBdmOrderItems(String orderId) {

        return bdmOrderItemMapper.getBdmOrderItems(orderId);
    }


    /**
     * 根据订单项退款
     */
    @Override
    public void refund(List<BdmOrderItem> bdmOrderItems, Long payType, Long userId) {
        BdmOrder bdmOrder =new BdmOrder();
        for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
             bdmOrder = bdmOrderService.lambdaQuery().eq(BdmOrder::getId, bdmOrderItem.getOrderId()).one();
            if (ObjectUtils.isEmpty(bdmOrder)){
                throw new RuntimeException("订单不存在");
            }
            //用户
            BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
            //用户积分
            long integral = Long.parseLong(DefaultZeroValueUtil.getValue(bdmOrderItem.getDeductIntegral())) - Long.parseLong(DefaultZeroValueUtil.getValue(bdmOrderItem.getGainIntegral()));
            //余额积分变动集合
            List<BdmBalanceChange> bdmBalanceChanges = new ArrayList<>();
            //增加积分
            if (bdmOrder.getOrderType() == 1) {
                if (integral > 0) {
                    bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                            userId,
                            bdmOrderItem.getOrderId(),
                            Long.toString(integral),
                            bdmUser.getCreditScore(),
                            String.valueOf(Long.parseLong(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore())) + integral),
                            Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                            Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                            BdmBalanceChangeEnum.CUSTOMER_REFUND_RETREAT_INTEGRAL.getDescription()
                    ));
                    bdmUser.setCreditScore(String.valueOf(Long.parseLong(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore())) + integral));//回滚积分
                }
            }
            //余额
            String payMoney = bdmOrder.getPayMoney();
            BigDecimal bigDecimal = new BigDecimal(payMoney);
            String deliveryCost = bdmOrder.getDeliveryCost();
            BigDecimal deliveryCost1 = new BigDecimal(deliveryCost);
            BigDecimal subtract = bigDecimal.subtract(deliveryCost1);
            if (payType.equals(BdmOrderEnum.BALANCE.getType())) {
                //插入余额积分变动表
                //-----------------------添加 余额 积分 变动 明细集合------------------------
                //增加余额
                if (subtract.compareTo(BigDecimal.ZERO) > 0) {
                    bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                            userId,
                            bdmOrderItem.getOrderId(),
                            subtract.toString(),
                            bdmUser.getRemainingSum().toString(),
                            bdmUser.getRemainingSum().add(subtract).toString(),
                            Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                            Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                            BdmBalanceChangeEnum.CUSTOMER_REFUND_RETREAT_BALANCE.getDescription()
                    ));
                }
                //-----------------------添加 余额 积分 变动 明细集合结束-----------------------
                //本单扣除积分减去 本单获取积分
                bdmUser.setRemainingSum(bdmUser.getRemainingSum().add(bdmOrderItem.getGoodPrice()));//回滚余额
            }else if (payType.equals(BdmOrderEnum.THIRD_PARTY.getType())) {
                //退款接口
                distributionService.polymerizationPay(subtract.toString(),bdmOrder.getId());
            }


            //}
            //批量修改余额积分变动
            bdmBalanceChangeService.saveBatch(bdmBalanceChanges);

            bdmUser.setTotalConsumeMomey(new BigDecimal(bdmUser.getTotalConsumeMomey()).subtract(bdmOrderItem.getGoodPrice()).toString());//回滚累积消费金额
            //修改用户信息
            bdmUserService.updateById(bdmUser);
        }
        //减少收益
            /*
              1.判断是否是大礼包只有大礼包才有收益
              2.去分销提成记录表 查询收益   状态为 未结算
              3.扣除用户 佣金
              4.修改用户 信息
              5. 修改分销提成记录 为  无效佣金
             */
        // if (bdmOrderItem.getGoodTypeName().equals(BdmGoodEnum.GIFT_PACKS.getDescription())){//判断
        List<BdmRoyaltyRecord> bdmRoyaltyRecords = bdmRoyaltyRecordService.lambdaQuery()
                .eq(BdmRoyaltyRecord::getOrderId, bdmOrder.getId())
                .eq(BdmRoyaltyRecord::getStatus,"1").list(); //未结算的

        for(BdmRoyaltyRecord bdmRoyaltyRecord:bdmRoyaltyRecords){
            if (!ObjectUtils.isEmpty(bdmRoyaltyRecord)){
                bdmRoyaltyRecord.setStatus("3");//无效佣金
                BdmUser bdmUser1 = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, bdmRoyaltyRecord.getSysUserid()).one();
                bdmUser1.setEarnings(bdmUser1.getEarnings().subtract(bdmRoyaltyRecord.getAmount()));//扣除用户佣金
                //更新收益
                bdmUserMapper.updateBdmUser(bdmUser1);
                bdmRoyaltyRecordService.updateById(bdmRoyaltyRecord); //修改分销提成记录 为  无效佣金
            }
        }
    }


    /**
     * 根据订单项退款 含运费
     */
    @Override
    public void refundOrder(List<BdmOrderItem> bdmOrderItems, Long payType, Long userId) {
        BdmOrder bdmOrder =new BdmOrder();
        for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
            bdmOrder = bdmOrderService.lambdaQuery().eq(BdmOrder::getId, bdmOrderItem.getOrderId()).one();
            if (ObjectUtils.isEmpty(bdmOrder)){
                throw new RuntimeException("订单不存在");
            }
            //用户
            BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
            //用户积分
            long integral = Long.parseLong(DefaultZeroValueUtil.getValue(bdmOrderItem.getDeductIntegral())) - Long.parseLong(DefaultZeroValueUtil.getValue(bdmOrderItem.getGainIntegral()));
            //余额积分变动集合
            List<BdmBalanceChange> bdmBalanceChanges = new ArrayList<>();
            //增加积分
            if (integral > 0) {
                bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                        userId,
                        bdmOrderItem.getOrderId(),
                        Long.toString(integral),
                        bdmUser.getCreditScore(),
                        String.valueOf(Long.parseLong(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore())) + integral),
                        Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                        Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                        BdmBalanceChangeEnum.CUSTOMER_REFUND_RETREAT_INTEGRAL.getDescription()
                ));
                bdmUser.setCreditScore(String.valueOf(Long.parseLong(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore())) + integral));//回滚积分
            }
            //余额
            if (payType.equals(BdmOrderEnum.BALANCE.getType())) {
                //插入余额积分变动表
                //-----------------------添加 余额 积分 变动 明细集合------------------------
                //增加余额
                String payMoney = bdmOrder.getPayMoney();
                BigDecimal bigDecimal = new BigDecimal(payMoney);
                bdmBalanceChanges.add(BdmBalanceChange.getBdmBalanceChange(
                        userId,
                        bdmOrderItem.getOrderId(),
                        payMoney,
                        bdmUser.getRemainingSum().toString(),
                        bdmUser.getRemainingSum().add(bigDecimal).toString(),
                        Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                        Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                        BdmBalanceChangeEnum.CUSTOMER_REFUND_RETREAT_BALANCE.getDescription()
                ));
                //-----------------------添加 余额 积分 变动 明细集合结束-----------------------
                //本单扣除积分减去 本单获取积分
                bdmUser.setRemainingSum(bdmUser.getRemainingSum().add(bigDecimal));//回滚余额
            }else if (payType.equals(BdmOrderEnum.THIRD_PARTY.getType())) {
                //退款接口
                distributionService.polymerizationPay(bdmOrder.getPayMoney(),bdmOrder.getId());
            }


            //}
            //批量修改余额积分变动
            bdmBalanceChangeService.saveBatch(bdmBalanceChanges);

            bdmUser.setTotalConsumeMomey(new BigDecimal(bdmUser.getTotalConsumeMomey()).subtract(bdmOrderItem.getGoodPrice()).toString());//回滚累积消费金额
            //修改用户信息
            bdmUserService.updateById(bdmUser);
        }
        //减少收益
            /*
              1.判断是否是大礼包只有大礼包才有收益
              2.去分销提成记录表 查询收益   状态为 未结算
              3.扣除用户 佣金
              4.修改用户 信息
              5. 修改分销提成记录 为  无效佣金
             */
        // if (bdmOrderItem.getGoodTypeName().equals(BdmGoodEnum.GIFT_PACKS.getDescription())){//判断
        List<BdmRoyaltyRecord> bdmRoyaltyRecords = bdmRoyaltyRecordService.lambdaQuery()
                .eq(BdmRoyaltyRecord::getOrderId, bdmOrder.getId())
                .eq(BdmRoyaltyRecord::getStatus,"1").list(); //未结算的

        for(BdmRoyaltyRecord bdmRoyaltyRecord:bdmRoyaltyRecords){
            if (!ObjectUtils.isEmpty(bdmRoyaltyRecord)){
                bdmRoyaltyRecord.setStatus("3");//无效佣金
                BdmUser bdmUser1 = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, bdmRoyaltyRecord.getSysUserid()).one();
                bdmUser1.setEarnings(bdmUser1.getEarnings().subtract(bdmRoyaltyRecord.getAmount()));//扣除用户佣金
                //更新收益
                bdmUserMapper.updateBdmUser(bdmUser1);
                bdmRoyaltyRecordService.updateById(bdmRoyaltyRecord); //修改分销提成记录 为  无效佣金
            }
        }
    }
}
